import React, { useState, useRef } from 'react';
import { useModel, } from 'umi';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ProFormInstance } from '@ant-design/pro-form';
import { MyContent } from '@/components/MyUI';
import * as api from '@/services/vpnServerDeploy';
import { Badge, Button, Descriptions, Popconfirm, Tag } from 'antd';
import Form from './Form';
import ReportForm from './ReportForm';
import { CheckCircleFilled, ClockCircleFilled, CloseCircleFilled, PauseCircleFilled, PlusOutlined } from '@ant-design/icons';
import * as c from '@/services/consts';
import * as utils from '@/utils/utils';

const OrderList: React.FC = () => {

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const { hasRight } = useModel('useAuthModel');

  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [formReportVisible, setFormReportVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.VpnServerDeploy|undefined>(undefined);

  
  const handleSubmit = async (data: API.VpnServerDeployForm | undefined) => {
    let result: API.Result;
    if(current){
      result = await api.update({
        ...current,
        ...data
      });
      if (result && result.success) {
        setCurrent(undefined);
        setFormVisible(false);
        actionRef?.current?.reload();
      }
    }
    else{
      result = await api.add(data);
      if (result && result.success) {
        setCurrent(undefined);
        setFormVisible(false);
        actionRef?.current?.reload();
      }
    }
  };
  
  const handlePublishSubmit = async (id: string) => {
    const result = await api.publish({ id: id });
    if (result.success) {
      actionRef.current?.reload();
    }
  };
  
  const handleCloseSubmit = async (id: string) => {
    const result = await api.close({ id: id });
    if (result.success) {
      actionRef.current?.reload();
    }
  };

  let columns: ProColumns<API.VpnServerDeploy>[] = [
    {
      title: '状态',
      align: 'center',
      width: 80,
      dataIndex: 'status',
      sorter: (a, b) => a.status - b.status,
      search: false,
      // valueEnum: {
      //   true: { status: 'Success' },
      //   false: { status: 'Error' },
      // },
      renderText: (val) => {
        return val == 2 ? <Tag color='#52c41a'>完成</Tag>
        : val == 3 ? <Tag color='error'>关闭</Tag>
        : val == 1 ? <Tag color='blue'>安装中</Tag> 
        : <Tag color='orange'>待运行</Tag> ;
        // return val == 2 ? (
        //   <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        // ) : val == 3 ? (
        //   <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        // ): val == 1 ? (
        //   <Badge count={<ClockCircleFilled style={{ color: 'orange' }} />} />
        // ): (
        //   <Badge count={<PauseCircleFilled style={{ color: 'orange' }} />} />
        // );
      },
      // filters: [
      //   { text: '启用', value: true },
      //   { text: '禁用', value: false },
      // ],
    },
    {
      title: '版本',
      dataIndex: 'id',
      width: 200,
      sorter: true,
    },
    {
      title: '部署类型',
      dataIndex: 'type',
      width: 100,
      search: false,
      sorter: true,
      render:(_,record)=>{
        return c.getObjectText(c.ServerDeployTypes, record.config?.type);
      }
    },
    {
      title: 'UDP',
      dataIndex: 'udp',
      width: 80,
      search: false,
      sorter: true,
      render:(_,record)=>{
        return record.udp == true ? <Tag color='success'>启用</Tag> : <Tag color='error'>禁用</Tag>
      }
    },
    {
      title: '服务器类型',
      dataIndex: 'serverType',
      width: 120,
      search: false,
      sorter: true,
      render:(_,record)=>{
        return c.getObjectText(c.ServerDeployServerTypeOptions, record.serverType);
      }
    },
    {
      title: '操作结果',
      dataIndex: 'config',
      search: false,
      sorter: false,
      render:(_,record)=>{
        return record.config.actions?.map((act) =>{
          return (
          <Descriptions
            size="small"
            column={6}
            contentStyle={{ minWidth:600 }}
            title={<span style={{fontWeight:'lighter',fontSize:14}}>{c.getObjectText(c.ServerDeployTypes, act.action)}</span>}
          >
            {utils.listHtoV(act.servers, 6)?.map((val) => {
              return (
                <Descriptions.Item label="" contentStyle={{marginTop:-15}}>
                  <Tag color=''>
                  <Badge count={val.success == true ? <CheckCircleFilled style={{ color: '#52c41a',marginTop:-3 }} /> 
                  : val.success == false ? <CloseCircleFilled style={{ color: '#f50',marginTop:-3 }} /> : <ClockCircleFilled style={{ color: '#999',marginTop:-3 }} />} />&nbsp;
                    {val.id} [{val.ip}]
                  </Tag>
                </Descriptions.Item>
              );
            })}
          </Descriptions>
          );
        });
      }
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      width:100,
      search: false,
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
      width: 150,
      search: false,
      sorter: true,
    },
    {
      title: '创建人',
      align: 'center',
      width: 120,
      dataIndex: 'createUser',
      sorter: false,
      search: false,
    },
    // {
    //   title: '修改时间',
    //   dataIndex: 'updateTime',
    //   align: 'center',
    //   width: 150,
    //   search: false,
    //   sorter: true,
    // },
    // {
    //   title: '修改人',
    //   align: 'center',
    //   width: 120,
    //   dataIndex: 'updateUser',
    //   sorter: false,
    //   search: false,
    // },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 150,
      render: (_, record) => {
        let cmps = [];

        if (hasRight('vpnserverdeploy_update')) {
          cmps.push(
            <a
              key="deploy_edit"
              onClick={() => {
                setCurrent(record);
                setFormVisible(true);
              }}
            >编辑
            </a>,
          );
          if(record.status == 0){
            cmps.push(
              <Popconfirm
              key="deploy_publish"
              title="确定要发布部署任务吗?"
              onConfirm={async () => {
                await handlePublishSubmit(record.id);
              }}
            >
              <a>发布</a>
            </Popconfirm>,
            );
          }
          if(record.status == 0 || record.status == 1){
            cmps.push(
              <Popconfirm
              key="deploy_close"
              title="确定要关闭部署任务吗?"
              onConfirm={async () => {
                await handleCloseSubmit(record.id);
              }}
            >
              <a>关闭</a>
            </Popconfirm>,
            );
          }
          if(record.status != 0){
            cmps.push(
              <a
                key="deploy_report"
                onClick={() => {
                  setCurrent(record);
                  setFormReportVisible(true);
                }}
              >部署结果
              </a>,
            );
          }
        }       

        return cmps;
      },
    },
  ]);

  return (
    <MyContent>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        formRef={formRef}
        search={{
          defaultCollapsed: false,
        }}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        columns={columns}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];

          if (hasRight('vpnserverdeploy_create')) {
            toolbarDoms.push([
              <Button
                type="primary"
                key="deploy_create"
                onClick={() => {
                  setCurrent(undefined);
                  setFormVisible(true);
                }}
              >
                <PlusOutlined />新建
              </Button>,
            ]);
          }
          return toolbarDoms;
        }}
        pagination={{
          defaultPageSize: 15,
          pageSizeOptions: ['15', '30', '60', '100'],
          hideOnSinglePage: true,
          // current: pageCurrent,
          // total: totalCount,
        }}
        request={api.list}
      />
      <Form
        visible={formVisible}
        current={current}
        onCancel={() => {
          setFormVisible(false);
        }}
        onSubmit={handleSubmit}
      />
      <ReportForm
        visible={formReportVisible}
        current={current}
        onCancel={() => {
          setFormReportVisible(false);
        }}
      />
    </MyContent>
  );
};

export default OrderList;
